import React from 'react'
import {
  View,
  StyleSheet,
  Text,
  Image,
  TextInput,

  Keyboard,
  TouchableOpacity
} from 'react-native'
import { StackActions } from 'react-navigation'
import * as Animatable from 'react-native-animatable'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import { getAuthSmsCode, mobileChange } from 'src/utils/RequestAPI'
import { SmsCodeReg, PhoneReg } from 'src/utils/RegUtil'
import { ShowLoading, DismissLoading } from 'src/utils/ToastUtil'

/* redux */
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION
} from 'src/store/actions/userinfo'
import CustomButton from 'src/components/button/CustomButton'

const AnimatableTouchableOpacity = Animatable.createAnimatableComponent(
  CustomButton
)

const mapActiontoProps = dispatch => ({
  updateUserInfoState (payload) {
    dispatch({
      type: UPDATE_USERINFO_ACTION,
      payload: {
        ...payload
      }
    })
  }
})
@connect(
  ({ userinfo }) => ({
    userinfo
  }),
  mapActiontoProps
)
class CommonChangePhone extends BasePage {
  state = {
    header: {
      headerBg: 'transparent'
    },
    mobile: '',
    mobileValid: false,
    mobileTip: '',
    code: '',
    codeTip: '',
    smsButtonClicked: false,
    smsButtonText: '发送验证码',
    smsTime: '',
    nextCheck: false
  }

  childRender () {
    const {
      mobile,
      mobileValid,
      mobileTip,
      smsButtonText,
      smsButtonClicked,
      smsTime,
      code,
      codeTip
    } = this.state
    const { nextButtonEnable } = this.state
    return (
      <KeyboardAwareScrollView
        contentContainerStyle={styles.container}
        enableAutomaticScroll={true}
        keyboardShouldPersistTaps="handled"
      >
        <Image
          style={styles.logo}
          source={require('@/imgC/login/logo_bg.png')}
        />
        <Text style={styles.title}>更换手机号</Text>
        <View style={styles.mobileBox}>
          <View style={styles.prefixBox}>
            <Text style={styles.prefix}>+86</Text>
          </View>
          <TextInput
            style={styles.itemTextInput}
            maxLength={11}
            placeholder="输入手机号码"
            placeholderTextColor="#999999"
            value={mobile}
            keyboardType="number-pad"
            clearButtonMode="while-editing"
            selectionColor="#FED201"
            autoFocus={false}
            onChangeText={this.mobileChanged}
          />
        </View>
        <Text style={styles.mobileTip}>{mobileTip}</Text>
        {!smsButtonClicked && (
          <AnimatableTouchableOpacity
            style={[styles.smsButton, mobileValid && styles.smsButtonEnable]}
            transition="backgroundColor"
            onPress={this.getSmsButtonClick}
          >
            <Animatable.Text
              style={[
                styles.smsButtonText,
                mobileValid && styles.smsButtonTextEnable
              ]}
              transition="color"
            >
              获取验证码
            </Animatable.Text>
          </AnimatableTouchableOpacity>
        )}
        {smsButtonClicked && (
          <View style={[styles.mobileBox, styles.smsBox]}>
            <TextInput
              style={styles.itemTextInput}
              placeholder="短信验证码"
              placeholderTextColor="#999999"
              value={code}
              clearButtonMode="while-editing"
              textContentType="oneTimeCode"
              keyboardType="number-pad"
              selectionColor="#FED201"
              onChangeText={this.smsCodeChanged}
            />
            <CustomButton onPress={this.getSmsButtonClick}>
              <Text
                style={[
                  styles.smsText,
                  mobileValid && smsTime === '' && styles.smsTextEnable
                ]}
              >
                {smsButtonText}
              </Text>
            </CustomButton>
          </View>
        )}
        <Text style={styles.mobileTip}>{codeTip}</Text>
        <AnimatableTouchableOpacity
          style={[
            styles.cc,
            styles.nextButton,
            nextButtonEnable && styles.nextButtonEnable
          ]}
          transition="backgroundColor"
          onPress={this.nextButtonClick}
        >
          <Image source={require('@/imgC/login/next.png')} />
        </AnimatableTouchableOpacity>
      </KeyboardAwareScrollView>
    )
  }

  static getDerivedStateFromProps (props, state) {
    return CommonChangePhone.checkNextButtonEnable(state)
  }

  static checkNextButtonEnable (state) {
    const { mobileValid, code } = state
    const nextButtonEnable = mobileValid && SmsCodeReg.test(code)
    console.log('nextButtonEnable', nextButtonEnable)
    return {
      nextButtonEnable
    }
  }

  mobileChanged = mobile => {
    mobile = mobile || ''
    const mobileValid = PhoneReg.test(
      mobile
    )
    this.setState({ mobile, mobileValid })
  }

  getSmsButtonClick = () => {
    Keyboard.dismiss()
    ShowLoading()
    this.smsButtonClick().then((code) => {
      this.setState({
        code, // todo
        smsButtonClicked: true
      })
    }).finally(() => {
      DismissLoading()
    })
  }

  smsTimer = null

  smsButtonClick = () => {
    return new Promise((resolve, reject) => {
      const {
        mobile,
        mobileValid
      } = this.state
      if (mobileValid && !this.smsTimer) {
        return getAuthSmsCode({ params: { mobile } }).then(res => {
          this.handleTimer()
          resolve(res.data.vcode)
        }).catch(() => {
          reject()
        })
      } else {
        reject()
      }
    })
  }

  handleTimer = () => {
    this.smsTimer = setInterval(() => {
      let { smsTime, smsButtonText } = this.state
      if (smsTime === '') {
        smsTime = 60
        smsButtonText = `已发送(${smsTime}s)`
      } else if (smsTime === 0) {
        smsTime = ''
        smsButtonText = `重新发送`
        clearInterval(this.smsTimer)
        this.smsTimer = null
      } else {
        smsTime = smsTime - 1
        smsButtonText = `已发送(${smsTime}s)`
      }
      this.setState({
        smsButtonText,
        smsTime
      })
    }, 1000)
  }

  smsCodeChanged = code => {
    this.setState({
      code
    })
  }

  nextButtonClick = () => {
    const { nextButtonEnable } = this.state
    if (nextButtonEnable) {
      const { mobile, code } = this.state
      const { userinfo: { userId: identifier } } = this.props
      const params = {
        mobile,
        code,
        identifier,
        type: 'userId'
      }
      ShowLoading()
      mobileChange({ params }).then(res => {
        console.log('mobileChange', res)
        const { userinfo, updateUserInfoState, navigation: { state: { params: { callback } = {} } } } = this.props
        const { B = {}, C = {} } = userinfo
        updateUserInfoState({
          ...userinfo,
          mobile,
          B: {
            ...B,
            mobile
          },
          C: {
            ...C,
            mobile
          }
        })
        callback && callback(mobile)
        setImmediate(() => {
          this.goBack()
        })
      }).finally(() => {
        DismissLoading()
      })
    }
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.smsTimer && clearInterval(this.smsTimer)
  }
}
export default CommonChangePhone

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    position: 'relative',
    paddingLeft: ScaleS(34),
    paddingRight: ScaleS(29)
  },
  cc: {
    justifyContent: 'center',
    alignItems: 'center'
  },
  logo: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: ScaleS(197),
    height: ScaleS(215),
    resizeMode: 'contain'
  },
  title: {
    marginTop: ScaleS(150),
    alignSelf: 'flex-start',
    height: ScaleS(55),
    fontSize: ScaleT(33),
    fontWeight: '600',
    color: '#333333'
  },
  mobileBox: {
    marginTop: ScaleS(51),
    height: ScaleS(50),
    width: ScaleS(312),
    backgroundColor: 'rgba(244,244,244,0.6)',
    borderRadius: 5,
    flexDirection: 'row',
    alignItems: 'center'
  },
  prefixBox: {
    width: ScaleS(57),
    height: ScaleS(24),
    borderRightColor: '#BEBEBE',
    borderRightWidth: ScaleS(1),
    borderStyle: 'solid',
    marginRight: ScaleS(2),
    alignItems: 'center',
    justifyContent: 'center'
  },
  prefix: {
    fontSize: ScaleT(17),
    fontWeight: '500',
    color: '#9E9E9E'
  },
  itemTextInput: {
    flex: 1,
    padding: 0,
    paddingLeft: ScaleT(15),
    color: '#444444',
    fontWeight: '500',
    fontSize: ScaleT(16),
    height: ScaleS(50),
    textAlignVertical: 'center'
  },
  mobileTip: {
    marginTop: ScaleS(6),
    height: ScaleS(17),
    fontSize: ScaleT(12),
    fontWeight: '400',
    color: '#D02202',
    alignSelf: 'flex-start'
  },
  smsButton: {
    marginTop: ScaleS(7),
    height: ScaleS(50),
    width: ScaleS(312),
    borderRadius: 5,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#D4D4D4'
  },
  smsButtonEnable: {
    backgroundColor: '#000000'
  },
  smsButtonText: {
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#FFFFFF'
  },
  smsButtonTextEnable: {
    color: '#FFFFFF'
  },
  smsBox: {
    marginTop: ScaleS(7)
  },
  smsText: {
    width: ScaleS(102),
    textAlign: 'center',
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#D0D0D0'
  },
  smsTextEnable: {
    color: '#444444',
    fontWeight: '500',
    fontSize: ScaleT(16)
  },
  nextButton: {
    marginTop: ScaleS(21),
    alignSelf: 'flex-end',
    width: ScaleS(70),
    height: ScaleS(70),
    backgroundColor: 'rgba(255, 216, 16, 0.3)',
    borderRadius: ScaleS(35)
  },
  nextButtonEnable: {
    backgroundColor: 'rgba(255, 216, 16, 1)'
  }
})
